package com.ds.robot.assistant.job;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.component.MessageSender;
import com.ds.robot.assistant.entity.ReqMilestonesEntity;
import com.ds.robot.assistant.enums.Env;
import com.ds.robot.assistant.enums.MilestoneType;
import com.ds.robot.assistant.enums.TimePoint;
import com.ds.robot.assistant.service.ReqMilestonesService;
import com.ds.robot.assistant.vo.ReqMilestonesUploadVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Component
@Slf4j
public class MilestoneTipJob extends BaseJob {

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private ReqMilestonesService milestonesService;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy年M月d日");


    @Scheduled(cron = "0 0 7 * * *")
    public void sendMilestoneTip() {
        queryAndSendTodayReqMilestoneTip(Env.TEST);
    }

    @Scheduled(cron = "0 40 8 * * *")
    public void sendMilestoneTipProd() {
        queryAndSendTodayReqMilestoneTip(Env.PROD);
    }


    public void queryAndSendTodayReqMilestoneTip(Env env) {
        List<ReqMilestonesEntity> list = milestonesService.queryTodayMilestone();
        sendReqMilestoneTip(null, list, env);
    }

    public void queryAndSendReqMilestoneTipByDate(String date, Env env) {
        List<ReqMilestonesEntity> list = milestonesService.queryMilestoneByDate(date);
        log.info("查询{}里程碑，数量={}", date, Optional.ofNullable(list).map(List::size).orElse(0));
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
        sendReqMilestoneTip(localDate, list, env);
    }

    public void sendReqMilestoneTip(LocalDate localDate, List<ReqMilestonesEntity> list, Env env) {
        if (CollectionUtils.isEmpty(list)) {
            log.info("今天{}没有里程碑，任务结束", localDate != null ? localDate.toString() : "");
            return;
        }
        List<ReqMilestonesUploadVO> voList = list.stream().map(entity -> {
            ReqMilestonesUploadVO vo = new ReqMilestonesUploadVO();
            vo.setReqName(entity.getReqName());
            vo.setTimePoint(TimePoint.getDescriptionByValue(entity.getTimePoint()));
            vo.setReminderMessage(StringUtils.hasText(entity.getReminderMessage()) ? entity.getReminderMessage() : MilestoneType.getDescriptionByValue(entity.getMilestoneType()));
            List<String> split = Splitter.onPattern("[,，]").trimResults().omitEmptyStrings().splitToList(entity.getReminderUser());

            if (!CollectionUtils.isEmpty(split)) {
                vo.setReminderUsers(split.stream().map(name -> " @" + name).collect(Collectors.joining()));
            }
            return vo;
        }).collect(Collectors.toList());

        String message = getMessage(localDate, voList);
        if (StringUtils.hasText(message)) {
            messageSender.sendMessage(message, env);
        }
    }

    private String getMessage(LocalDate localDate, List<ReqMilestonesUploadVO> list) {
        String date;
        if (localDate != null) {
            date = localDate.format(FORMATTER);
        } else {
            date = LocalDate.now().format(FORMATTER);
        }
        StringBuilder builder = new StringBuilder("# [" + date + "] 里程碑提醒\n");
        if (Objects.isNull(list)) {
            list = Lists.newArrayList();
        }
        // Map<String, String> nameToIdMap = super.getUserNameToIdMap();
        for (int i = 0; i < list.size(); i++) {
            ReqMilestonesUploadVO vo = list.get(i);
            builder.append("### ").append(i + 1).append(".").append(vo.getReqName())
                    .append("  <font color=\"warning\">[").append(vo.getTimePoint()).append("]</font>")
                    .append("  <font color=\"info\">").append(vo.getReminderMessage()).append("</font>");
            if (StringUtils.hasText(vo.getReminderUsers())) {
                super.appendUserIdOneLine(vo.getReminderUsers(), builder, log);
                builder.append("\n");
            }
        }
        builder.append("\n\n\n <@wjn> <@w> <@所有人> \n请悉知~");
        return builder.toString();
    }


    public static String[] splitByCommas(String str) {
        // 使用正则表达式匹配中英文逗号
        return str.split("[,，]");
    }

    public static Iterable<String> splitByCommas2(String str) {
        return Splitter.onPattern("[,，]").trimResults().omitEmptyStrings().split(str);
    }

}
